package com.fcai.microserv.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class JacksonLocalDateFormatter {

    @JsonComponent
    // 默认格式为：2016-10-10T10:10:10
    public static class LocalDateSerializer extends JsonSerializer<LocalDate> {
        @Value("${spring.mvc.format.date:yyyy-MM-dd}")
        private String pattern;
        @Override
        public void serialize(LocalDate value, JsonGenerator g, SerializerProvider serializers) throws IOException, JsonProcessingException {
            g.writeString(value.format(DateTimeFormatter.ofPattern(pattern)));
        }
    }

    @JsonComponent
    public static class LocalDateDeserializer extends JsonDeserializer<LocalDate> {
        @Value("${spring.mvc.format.date:yyyy-MM-dd}")
        private String pattern;
        @Override
        public LocalDate deserialize(JsonParser p, DeserializationContext content) throws IOException, JsonProcessingException {
            String text = p.getText().trim();
            return LocalDate.parse(text, DateTimeFormatter.ofPattern(pattern));
        }
    }
}
